<template>
  <div class="app-container">
    <el-row :gutter="20" class="toolbar" type="flex" justify="space-between">
      <!-- 左侧组合 -->
      <el-col :span="16">
        <el-row :gutter="15">
          <el-col :span="10">
            <el-input
                v-model="searchKey"
                placeholder="输入接口名称搜索"
                @keyup.enter.native="handleSearch">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
          </el-col>
        </el-row>
      </el-col>

      <!-- 右侧按钮 -->
      <el-col :span="8" class="text-right">
        <el-button type="primary" @click="handleCreate">绑定权限组</el-button>
      </el-col>
    </el-row>
    <!-- 数据表格 -->
    <el-table
        :data="groupList"
        border
        stripe
        style="width: 100%"
        class="data-table">
      <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center">
      </el-table-column>

      <el-table-column
          prop="name"
          label="权限组名称"
          min-width="150">
      </el-table-column>

      <el-table-column
          prop="createTime"
          label="绑定时间"
          min-width="150">
      </el-table-column>

      <el-table-column
          prop="creator"
          label="绑定人"
          min-width="150">
      </el-table-column>


      <el-table-column
          label="操作"
          min-width="150"
          align="center">
        <template #default="{row}">
          <el-button
              type="text"
              size="small"
              style="color: #ff4d4f"
              @click="handleDelete(row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!-- 应用详情对话框 -->
    <el-dialog
        title="应用详情"
        :visible.sync="detailDialogVisible"
        width="600px">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="应用ID">
          <span>{{ detailData.appId }}</span>
        </el-form-item>
        <el-form-item label="应用名称">
          <span>{{ detailData.appName }}</span>
        </el-form-item>
        <el-form-item label="创建人">
          <span>{{ detailData.creator }}</span>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ detailData.createTime }}</span>
        </el-form-item>
        <el-form-item label="密钥">
          <span>{{ detailData.secret || '无' }}</span>
        </el-form-item>
        <el-form-item label="应用描述">
          <span>{{ detailData.remark || '暂无描述' }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 绑定接口地址对话框 -->
    <el-dialog
        title="绑定权限组"
        :visible.sync="bindDialogVisible"
        @close="handleDialogClose"
        width="600px">

      <!-- 搜索接口 -->
      <el-input
          v-model="searchApiKey"
          placeholder="搜索权限组"
          @keyup.enter.native="handleApiSearch">
        <el-button slot="append" icon="el-icon-search" @click="handleApiSearch"></el-button>
      </el-input>

      <!-- 接口分页列表 -->
      <el-table
          ref="groupTable"
          :data="groupPageList"
          border
          stripe
          style="width: 100%"
          class="data-table">

        <el-table-column
            type="selection"
            width="55">
        </el-table-column>

        <el-table-column
            prop="name"
            label="权限组名称"
            min-width="150">
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleApiSizeChange"
          @current-change="handleApiCurrentChange"
          :current-page="groupCurrentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="groupPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="groupTotal">
      </el-pagination>

      <div slot="footer" class="dialog-footer">
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBindSubmit">绑定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {queryAppGroupPage, bindAppGroup, delBindGroup} from '@/api/gateway-app'
import {queryGroupPage} from "@/api/gateway-group";

export default {
  data() {
    return {
      searchKey: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      detailDialogVisible: false,
      detailData: {},
      groupList: [],
      bindDialogVisible: false,
      searchApiKey: '',
      groupPageList: [],
      groupCurrentPage: 1,
      groupPageSize: 10,
      groupTotal: 0,
      sysAppId: '',
    }
  },
  mounted() {
    this.sysAppId = this.$route.query.id
    this.loadData()
  },
  methods: {
    handleDialogClose() {
      if (this.$refs.groupTable) {
        this.$refs.groupTable.clearSelection();
      }
    },
    // 加载数据方法
    async loadData() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          keywords: this.searchKey,
          id: this.sysAppId,
        }
        const {data} = await queryAppGroupPage(params)
        this.groupList = data.records
        this.total = data.total
        // 同步分页信息（根据接口实际情况调整）
        this.currentPage = data.current
        this.pageSize = data.size
      } catch (error) {
        console.error('数据加载失败:', error)
      }
    },
    async queryApiPage() {
      const params = {
        page: this.groupCurrentPage,
        size: this.groupPageSize,
        keywords: this.searchApiKey,
        excludeAppId: this.sysAppId
      }
      const {data} = await queryGroupPage(params)
      this.groupPageList = data.records
      this.groupTotal = data.total
    },
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadData()
    },
    // 修改后的创建方法
    handleCreate() {
      this.bindDialogVisible = true
      this.queryApiPage()
    },
    handleDelete(row) {
      this.$confirm(`是否解除绑定的权限组 ${row.name}？`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await delBindGroup({id: row.id})
          this.$message.success(`删除成功`);
          await this.loadData()
        } catch (error) {

        }
      }).catch(() => {
        this.$message.info('操作已取消');
      });
    },
    handleApiSearch() {
      this.queryApiPage()
    },
    handleApiSizeChange(val) {
      this.groupPageSize = val;
    },
    handleApiCurrentChange(val) {
      this.groupCurrentPage = val;
    },
    async handleBindSubmit() {
      const selectedRows = this.$refs.groupTable.selection;
      console.log('选中的行:', selectedRows);
      const apiIds = selectedRows.map(item => item.id);
      try {
        const response = await bindAppGroup({
          sysAppId: this.sysAppId,
          groupId: apiIds
        })
        this.$message.success('绑定权限组成功')
        this.loadData()
        this.searchKey = ''
      } catch (error) {
        console.error('绑定失败:', error)
      } finally {
        this.bindDialogVisible = false;
      }
    }
  }
}
</script>

<style scoped>

/* 新增样式 */
.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-textarea {
  resize: vertical;
}

.toolbar {
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.data-table {
  margin-top: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.text-right {
  text-align: right;
}

.detail-dialog .el-form-item {
  margin-bottom: 15px;
}

.detail-dialog .el-form-item span {
  font-weight: bold;
  color: #333;
}

.detail-dialog .dialog-footer {
  text-align: right;
  padding: 10px 0;
}

.detail-dialog .el-dialog__body {
  padding: 20px 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
}
</style>